﻿using Autofac;
using Topshelf;
using System.Diagnostics;
using System.Threading;
using Elasticsearch.Synchronize.Monitor.Job;

namespace Elasticsearch.Synchronize.Monitor
{
    public class JobService : ServiceControl
    {
        private readonly IContainer _container;

        public JobService()
        {
            var builder = new Autofac.ContainerBuilder();
            builder.RegisterModule(new ServiceDependencyModule());
            _container = builder.Build();
        }

        public bool Start(HostControl hostControl)
        {
            #region EventJoin

            ThreadPool.QueueUserWorkItem(x =>
            {
                while (true)
                {
                    _container.Resolve<EventJoinJob>().Scan();
                    Thread.Sleep(2000);
                }
            });

            ThreadPool.QueueUserWorkItem(x => { _container.Resolve<EventJoinJob>().Finish(); });

            #endregion

            return true;
        }

        public bool Stop(HostControl hostControl)
        {
            foreach (ProcessThread thread in Process.GetCurrentProcess().Threads)
            {
                thread.Dispose();
            }

            return true;
        }
    }
}